<?php
/**
 * Created by IntelliJ IDEA.
 * User: 86135
 * Date: 2019/5/23
 * Time: 14:19
 */

namespace App\Http\Controllers;

use App\Model\User;
use App\Model\UserInfo;
use App\Model\Users;
use App\Model\UserLogs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Think\Exception;

class UserController extends Controller
{


    public function __construct()
    {
        //$this->middleware('auth');

        //$this->middleware('log')->only('index');

        // $this->middleware('subscribed')->except('store');
    }

    /**
     * 显示给定用户的概要文件.
     *
     * @param  int $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }

    public function relation(Request $req){
        $mode = $req->mode?$req->mode:'1_1';
        switch ($mode){
            case '1_1':
                {
                    //一对一
                    dump('--------------------------1_1----------------------------------');
                    //$user = User::find(3)->UserInfo()->get()->toArray();
                    $user = User::with('UserInfo')->get()->toArray();
                    dump($user);

                }
                break;
            case '1_n':
                {
                    dump('--------------------------1_n----------------------------------');
                    //一对多
                    //$user = Users::with('UserLogs')->where('id','=',22)->get()->toArray();
                    //$user = User::with('UserLogs')->get()->toArray();
                    $user = User::with('Article')->get()->toArray();
                    dump($user);
                }
                break;
            case 'n_1':
                {
                    //多对一
                    dump('--------------------------n_1----------------------------------');
                    //$data = User::find(1)->Country()->get()->toArray();
                    $data = User::with('Country')->get()->toArray();
                    dd($data);


                }
                break;
            case 'n_n':
                {
                    //多对多
                    dump('--------------------------n_n----------------------------------');
                   // $data = User::find(2)->Role()->get()->toArray();
                    $data = User::with('Role')->get()->toArray();
                    dd($data);
                }
                break;
            case 'n_n_n':
                {
                    //多对多
                    dump('--------------------------n_n----------------------------------');
                    // $data = User::find(2)->Role()->get()->toArray();
                    $data = User::with('Role','Country','Article','UserInfo','UserLogs')->get()->toArray();
                    dd($data);
                }
                break;
            default;
        }
    }
    public  function testWith(){
        $data = Users::with(['UserLogs'=>function($query){
            $query->select(['']);
        }])->get()->toArray();
        dd($data);
    }

    /**
     * 用户登录
     * @param $username
     * @param $password
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */

    public function tologin()
    {
        return view('user.login');
    }

    public function login(Request $req)
    {

        return redirect('auth/login');
    }

    public function toregist()
    {
        return view('user.regist');
    }

    public function regist(Request $req)
    {

        $parant = $req->parant ? $req->parant : '';
        $money = $req->money ? $req->money : 10000;//默认蚁商
        $username = $req->username;
        $password = $req->password? $req->password : 123456;//默认蚁商;
        $moneys= array(10000,100000);
        if (DB::table('users')->where('username', $username)->count()) {
          $this->sendMSG('用户已经存在');
        }
        if(!in_array(intval($money),$moneys)){
            $this->sendMSG('目前仅开放注册蚁商和初级代理');
        }
        if (!empty($parant)) {
            $parants = Users::select(['id', 'area_place'])->where('username', '=', $parant)->first()->toArray();
        }

        $user = [];
        $user['username'] = $username;
        $user['rg_money'] = $money;
        $user['user_level'] = $money == 10000 ? 1 : 2;//注册两个级别 1w为蚁商，10w为初级代理
        $user['parant_name'] = $parant;
        $user['password'] = md5($password);


        $user_id = Users::insertGetId($user);
        //更新位置
        if ($user_id > 0) {//如果有推荐人
            if (!empty($parants)) {
                $area_place = $parants['area_place'] . ',' . $user_id;
                Users::where('id', '=', $user_id)->update(['area_place' => $area_place]);

                // 分享奖励
                $this->re_share($parants['id'], $username, $money);

                //管理奖，管理奖跟上代人有关，所以有推荐关系的人才能进行结算管理奖，管理奖获取者为推荐人的位置信息
                $this->supervise($parants['area_place'], $money, $username);

            } else {
                Users::where('id', '=', $user_id)->update(['area_place' => $user_id]);
            }
            return redirect('/user/info');
        } else {
            $this->sendMSG();
        }

    }

    /**
     * 模拟购物接口
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */

    public function shoping(Request $req)
    {

        $username = $req->username;//购物用户名
        $money = $req->money;//购物金额
        $up_data = [];//获取管理奖的人
        $logs_data = [];//记录集合

        if (empty($username) || empty($money)) {
            exit("缺少用户名或金额");
        }

        $user = Users::select(['id', 'parant_name', 'area_place'])->where('username', '=', $username)->first()->toArray();
        if ($user['id'] != intval($user['area_place'])) {//有推荐人的情况下
            $users = Users::whereIn("id", explode(",", $user['area_place']))->orderBy('id', 'desc')->limit(10)->get(['id', 'username','money'])->toArray();//最高9层，包含了自己10查询到10层
            foreach ($users as $u) {
                if ($u['id'] == $user['id']) {
                    continue;
                }
                if ($u['username'] == $user['parant_name']) {//直推获取6%
                    $get_money = $money * 6 * 0.01;
                } else {
                    $get_money = $money * 0.75 * 0.01;
                }
                $up_data[] = array(
                    'id' => $u['id'],
                    'money' => $get_money,
                );
                $logs_data[] = array(
                    'user_id' => $u['id'],
                    'money' => $get_money,
                    'befor_money' => $u['money'],
                    'ofter_money' => $u['money']+$get_money,
                    'chenge_type' => 2,
                    'remark' => $username . '购物获得购物津贴',
                    'create_time' => time(),
                );

            }
            if (!empty($logs_data)) {
                DB::beginTransaction();
                try {
                    DB::table('user_logs')->insert($logs_data);
                    $this->batchUpdateUsersMoney($up_data);
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    exit("处理失败，请稍后重试");
                }

            }

        }
        return redirect('/user/log');
    }

    public function info(Request $req)
    {
        $username = $req->username;//用户名
        if (empty($username)) {
            $users = Users::select(['id', 'username', 'user_level', 'money', 'parant_name'])->orderBy('id', 'desc')->paginate(15)->toArray();
        } else {
            $users = Users::select(['id', 'username', 'user_level', 'money', 'parant_name'])->where('username', '=', $username)->orderBy('id', 'desc')->paginate(15)->toArray();
        }
        return view('user.users')->with('users', $users);
    }


    public function logs(Request $req)
    {
        $username = $req->username;//用户名
        if (empty($username)) {
            $logs =  DB::table('user_logs as l')
                ->join('users as u', 'u.id', '=', 'l.user_id')
                ->select(['l.*','u.username'])
                ->orderBy('l.id', 'desc')
                ->paginate(15)
                ->toArray();
            //$logs = UserLogs::orderBy('id', 'desc')->get(['id', 'user_id', 'remark', 'money', 'chenge_type'])->toArray();
        } else {
            $logs =  DB::table('user_logs as l')
                ->join('users as u', 'u.id', '=', 'l.user_id')
                ->select(['l.*','u.username'])
                ->where('u.username', $username)
                ->orderBy('l.id', 'desc')
                ->paginate(15)
                ->toArray();
        }
        return view('user.logs')->with('logs', $logs);
    }

    /**
     * 分享奖励处理函数
     * @param int $parant_id 分享的人的id
     * @param string $username 被分享人的名称
     * @param int $moeny 被分享人注册的金额
     */

    private function re_share($parant_id = 0, $username = '', $moeny = 0)
    {
        $share_nomey = 0;
        if ($moeny == 10000) {//蚁商30%
            $share_nomey = $moeny * 0.3;
        } else if ($moeny == 100000) {//初代理商 20%
            $share_nomey = $moeny * 0.2;
        }
        if ($share_nomey > 0) {//有金额的情况下进行奖励
            $money = Users::where('id', '=', $parant_id)->pluck('money')[0];
            //更新分享人金额
            Users::where('id', '=', $parant_id)->increment('money', $share_nomey);
            $this->user_log($parant_id, $share_nomey,$money, 1, '推荐:' . $username);
        }

    }


    /**理奖处理函数 ，批量处理
     * @param string $area_place 能发放管理奖的关系链
     * @param int $money 初始金额
     * @param string $username 新用户注册的名称
     * @return boolean
     */
    private function supervise($area_place = '', $money = 0, $username = '')
    {
        if (empty($area_place)) {
            return;
        }
        $user_level = $money == 10000 ? 1 : 2;//注册两个级别 1w为蚁商，10w为初级代理
        $super_money = $money * 0.3;//管理奖的初始金额
        $last_money = $super_money;//剩余金额
        $had_level = [];//已经领过的等级记录
        $up_data = [];//获取管理奖的人
        $logs_data = [];//记录集合

        $users = Users::where('user_level', '>', $user_level)->whereIn("id", explode(",", $area_place))->orderBy('id', 'desc')->get(['id', 'user_level','money'])->toArray();
        foreach ($users as $user) {
            if (in_array($user['user_level'], $had_level)) {//已经存在的等级无法再获取管理奖
                continue;
            }
            if ($last_money == 0) {//没有可分配的余额无法再进行
                break;
            }
            if ($user_level == 2 && $user['user_level'] <= 4) {//中级代理和高级代理无法获得初级代理的管理奖
                continue;
            }
            if (!empty($had_level) && max($had_level) >= $user['user_level']) {//存在比已经分配的等级低或者相等的情况下无法再获得管理奖
                continue;
            }
            $parant_level= $user['user_level'] >= 5 && $user_level==2 ? $user['user_level'] - 2 : $user['user_level'];//如果用户注册是初代里，则总代才能获取管理奖初级总代10%，中级总代20，高级总代30% 初级代理为2，初级总代为5，中级为6，高级为7
            if (empty($had_level)) {//未分分配的情况下的极差
                $diff = $parant_level - $user_level;//等级差
            } else {
                //已有分配下的级差
                $diff = $parant_level - max($had_level);
            }

            $get_money = $money * 0.1 * $diff;//等级差获取的金额。差1级得到10%，差两级得到20%，差3级得到30%
            if ($get_money > $last_money) {
                $get_money = $last_money;
            }

            $had_level[] = $user['user_level'];//记录获取的等级
            $last_money = $last_money - $get_money;//减去已领取的奖金

            $up_data[] = array(
                'id' => $user['id'],
                'money' => $get_money,
            );

            $logs_data[] = array(
                'user_id' => $user['id'],
                'money' => $get_money,
                'befor_money' => $user['money'],
                'ofter_money' => $user['money']+$get_money,
                'chenge_type' => 2,
                'remark' => $username . '注册获得管理奖',
                'create_time' => time(),
            );


        }
        DB::beginTransaction();
        try {
            DB::table('user_logs')->insert($logs_data);
            $this->batchUpdateUsersMoney($up_data);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }

    }

    public function test(Request $req)
    {
        $money = Users::where('username', '=', 'qweqwe')->pluck('money')[0];
      dump($money);
    }


    /**
     * 理奖处理函数,单个处理，利用回调机制
     * @param $parent  父类
     * @param $money 注册的金额
     * @param $last_money 剩余的奖金池
     * @param $max_level  当前最大的等级
     * @param $username
     */
    private function supervises($parent, $money, $last_money, $max_level, $username)
    {
        if ($last_money == 0) {
            return;
        }

        $user = Users::select(['id', 'parant_name','username', 'user_level','money'])->where('username', $parent)->first();
        if (empty($user)) {
            return;
        }
        $get_money = 0;
        if (($money ==10000 && $user['user_level'] > $max_level) || ($money==100000 && ['user_level']>=5 && $user['user_level'] > $max_level)) {


            $diff = $user['user_level'] >= 5 && $money==100000 ? $user['user_level'] - $max_level - 2 : $user['user_level'] - $max_level;//如果用户注册是初代里，则总代才能获取管理奖初级总代10%，中级总代20，高级总代30% 初级代理为2，初级总代为5，中级为6，高级为7
            $get_money = $money * 0.1 * $diff;//等级差获取的金额。差1级得到10%，差两级得到20%，差3级得到30%
            if ($get_money > $last_money) {
                $get_money = $last_money;
            }
            DB::beginTransaction();
            try{
                $logs_data = array(
                    'user_id' => $user['id'],
                    'money' => $get_money,
                    'befor_money' => $user['money'],
                    'ofter_money' => $user['money']+$get_money,
                    'chenge_type' => 2,
                    'remark' => $username . '注册获得管理奖',
                    'create_time' => time(),
                );
                DB::table('user_logs')->insert($logs_data);
                Users::where('id', '=', $user['id'])->increment('money', $get_money);
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
            }

        }
        if (!empty($user['parant_name'])) {
            if(($user['user_level'] > $max_level)){
                $max_level = $user['user_level'];
            }
            $last_money = $last_money - $get_money;
            $this->supervises($user['parant_name'], $money, $last_money, $max_level, $username);
        }

    }

    /**
     * 用户的简单金额变动记录
     * @param int $uid 记录的用户id
     * @param int $money 变动的金额
     * @param int $befor_money 变动钱的金额
     * @param int $chenge_type 变动类型;1 分享奖励，2管理奖
     * @param string $remark 备注
     */
    private function user_log($uid = 0, $money = 0,$befor_money=0, $chenge_type = 1, $remark = '')
    {
        $log = [];
        $log['user_id'] = $uid;
        $log['money'] = $money;
        $log['befor_money'] = $befor_money;
        $log['ofter_money'] = $befor_money+$money;
        $log['chenge_type'] = $chenge_type;
        $log['remark'] = $remark;
        $log['create_time'] = time();
        UserLogs::insertGetId($log);
    }


    /**
     * 批量更新用户的金额
     * @param array $values 更新用户的id 和金额
     */
    private function batchUpdateUsersMoney(array $values)
    {
        $final = [];
        $ids = [];
        $primary_key = 'id';//PRIMARY
        if (!count($values)) {
            return;
        }
        foreach ($values as $key => $val) {
            $ids[] = $val[$primary_key];
            foreach (array_keys($val) as $field) {
                if ($field !== $primary_key) {
                    $value = is_numeric($val[$field]) ? $val[$field] : "'$val[$field]'";
                    if ($field == 'money') {
                        $final[$field][] = 'WHEN `' . $primary_key . '` = ' . $val[$primary_key] . ' THEN ' . 'money+' . $value . ' ';
                    } else {
                        $final[$field][] = 'WHEN `' . $primary_key . '` = ' . $val[$primary_key] . ' THEN ' . $value . ' ';
                    }

                }
            }
        }
        $cases = '';
        foreach ($final as $k => $v) {
            $cases .= '`' . $k . '` = CASE ' . implode("", $v)
                . ' END, ';
        }
        $ids_str = implode(',', $ids);
        $cases = substr($cases, 0, -2);
        $up_sqls = "UPDATE `users` SET  $cases WHERE `$primary_key` IN($ids_str);";
        DB::update($up_sqls);
    }
    /**
     * ajax 返回数据
     * @param string  $msg 发送信息描述
     * @param string $code   发送信息的状态200为成功，其他为失败
     * @param array $data  发送的参数
     *
     */
    function sendMSG($msg='请求失败请稍后重试', $code='1', $data = []) {
        $arr = array(
            'msg' => $msg,
            'code' => $code,
            'data' => empty($data) ? "" : $data
            // 'data' => empty($data) ? "" : enGzip($data)
        );
        exit(json_encode($arr,320));
    }


}
